package com.topisv.tms.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.topisv.tms.entity.qimen.DeliveryOrderTask;
import com.topisv.tms.entity.qimen.OrderProcessConfig;
import com.topisv.tms.service.qimen.DeliveryOrderTaskService;
import com.topisv.tms.service.unprocessxml.UnProcessXmlService;
import com.topisv.tms.slf4j.MarkerConstant;
import com.topisv.tms.utils.InitProperties;

/**
 * 发货单任务提供类
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2015-5-8      CC            1.0           Create
 */
@Component
@Lazy(false)
public class DeliveryOrderTaskProvider implements InitializingBean {
	
	private static Logger logger = LoggerFactory.getLogger(DeliveryOrderTaskProvider.class);
	
//	private BlockingQueue<DeliveryOrderTask> tasks = new ArrayBlockingQueue<DeliveryOrderTask>(1000);
	
	@Autowired
	private DeliveryOrderTaskService service;
	@Autowired
	private UnProcessXmlService unProcessXmlService;

	private  static Map<String, Object> param = new HashMap<String, Object>(){{
		put("dispatchFlag", "1");
	}};

	
	public static Map<String, BlockingQueue<DeliveryOrderTask>> warehouseMap= new HashMap<>();
	
	@Scheduled(cron = "0/10 * * * * *")
	public void executor() {
		try {
			
			List<OrderProcessConfig> list = service.findOrderProcessConfigByIp();
			for(OrderProcessConfig o : list) {
				
				if(o.getStatus() == 1) {
					
					String warehouseCode = o.getWarehouseCode();
					BlockingQueue<DeliveryOrderTask> warehouseTask = warehouseMap.get(o.getWarehouseCode());
					
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String fromDate = sdf.format(DeliveryOrderTaskService.getDateBefore(new Date(), 6))+" 00:00:00";
					String  toDate = sdf.format(new Date())+" 23:59:59";
					
					param.put("warehouseCode", warehouseCode);
					param.put("fromDate", fromDate);
					param.put("toDate", toDate);
					
					logger.error(MarkerConstant.MONITOR_MARKE,"{}, {}队列剩余数量 ::{}", service.getNode() , o.getWarehouseCode(), warehouseTask.size());
					//满足仓库订单阀值,进行锁数据并查询数据；否则不进行查询
					if(unProcessXmlService.isMeetWaitOrderNumlessThreshold(param, o)) {
						service.lockData(param);
						List<DeliveryOrderTask> data = service.findData(warehouseCode);
						for (DeliveryOrderTask task : data) {
							if(!warehouseTask.contains(task)){
								warehouseTask.put(task);
							}
						}					
					}
				}
			}
			
		} catch (Exception e) {
			logger.error("DeliveryOrderTaskProvider case some error.", e);
		}
	}

	public static void  putTaskQueue(String warehouseCode, List<DeliveryOrderTask> dataList){
		try {
			BlockingQueue<DeliveryOrderTask> warehouseTask = warehouseMap.get(warehouseCode);

			logger.error(MarkerConstant.MONITOR_MARKE, "{}当前剩余队列数量 :: {}", warehouseCode, warehouseTask.size());
			for (DeliveryOrderTask data : dataList) {
				if (!warehouseTask.contains(data)) {
					warehouseTask.put(data);
				}
			}
			logger.error(MarkerConstant.MONITOR_MARKE, "{}设置完队列数量:: {}", warehouseCode, warehouseTask.size());
		} catch (Exception e) {
			logger.error("",e);
		}
		
	}
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		
		List<OrderProcessConfig> list = service.findOrderProcessConfigByIp();
		logger.error("总共线程数 : {}", list.size());
		
		for(OrderProcessConfig o : list){
			
			BlockingQueue<DeliveryOrderTask> taskQueue =  new ArrayBlockingQueue<DeliveryOrderTask>(5000);
			
			warehouseMap.put(o.getWarehouseCode(), taskQueue);
			
			DeliveryOrderTaskWorker threadTask = new DeliveryOrderTaskWorker(warehouseMap.get(o.getWarehouseCode()), service);
			threadTask.setName(service.getNode() + "_" + o.getWarehouseCode());
			logger.error("线程名称 : {}", service.getNode() + "_" + o.getWarehouseCode());
			threadTask.start();
		}
	}
}
